package com.gzx.plugin.tjzy.modular.call.receipt.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzx.plugin.tjzy.modular.call.predict.service.GzxPredictCallDbService;
import com.gzx.plugin.tjzy.modular.call.predict.vo.GzxPredictAllVo;
import com.gzx.plugin.tjzy.modular.call.receipt.bo.GzxReceiptBusinessStatisticBo;
import com.gzx.plugin.tjzy.modular.call.receipt.mapper.GzxHtCallReceiptBusinessMapper;
import com.gzx.plugin.tjzy.modular.call.receipt.service.GzxReceiptBusinessStatisticService;
import com.gzx.plugin.tjzy.modular.call.receipt.vo.GzxReceiptBusinessStatisticVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;

import java.util.List;

/**
 * @author xbl
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxReceiptBusinessStatisticServiceImpl implements GzxReceiptBusinessStatisticService {

    private final GzxHtCallReceiptBusinessMapper businessStatisticMapper;

    //线路
    private final GzxPredictCallDbService predictCallDbService;

    /**
     * 线路接通率
     */
    @DS("tjzy-async")
    @Override
    public Page<GzxReceiptBusinessStatisticVo> callerRate(GzxReceiptBusinessStatisticBo bo) {
        //把list转成page返回给前端
        Page<GzxReceiptBusinessStatisticVo> page = new Page<>(bo.getCurrent(), bo.getSize());

        int current = bo.getCurrent();
        int pageNum = (current - 1) * bo.getSize();
        bo.setCurrent(pageNum);

        List<GzxReceiptBusinessStatisticVo> list = businessStatisticMapper.callerRate(bo);
        //计算接通率，应答率
        for (GzxReceiptBusinessStatisticVo vo : list) {
            vo.setConnectRate(Double.parseDouble(String.format("%.2f", (double) vo.getConnectCall() / vo.getTotalCall())));
            vo.setRingRate(Double.parseDouble(String.format("%.2f", (double) vo.getConnectRing() / vo.getTotalCall())));
        }
        //根据主叫号码转换线路名称
        if (!list.isEmpty()) {
            List<GzxPredictAllVo> callerInfo = predictCallDbService.getCallerInfo(CommonDateUtil.currentMonth());
            //线路callerInfo的caller和activeLineVos的linName相同的，把lineName改成callerInfo的lineName
            for (GzxPredictAllVo predictAll : callerInfo) {
                for (GzxReceiptBusinessStatisticVo activeLineVo : list) {
                    if (!ObjectUtils.isEmpty(predictAll) && !StringUtils.isEmpty(predictAll.getCaller()) && predictAll.getCaller().equals(activeLineVo.getCaller())) {
                        activeLineVo.setCallName(predictAll.getCallName());
                    }
                }
            }
        }
        page.setRecords(list);

        long total = businessStatisticMapper.callerRateTotal(bo);
        page.setTotal(total);

        return page;
    }
}
